package com.moon.game.command.guest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.moon.game.command.BaseCmd;
import com.moon.game.command.RequestSession;
import com.moon.game.constants.Constants;
import com.moon.game.exception.GException;
import com.moon.game.message.ObjMessage;
import com.moon.game.service.PlayerService;
import com.moon.game.vos.PlayerVo;

public class Login extends BaseCmd{
	private static final Logger log = Logger.getLogger(Login.class);
	
	@Override
	protected void runOnce(RequestSession req) throws GException {
		switch (req.getStatus()) {
			case STATU_INIT:
				doInit(req);
				break;
			case STATU_CHECK:
				loginOrRegistPlayer(req);
				break;
			case STATU_RETURN:
				doResponse(req);
				break;
			default:
				break;
		}
	}
	
	protected void loginOrRegistPlayer(RequestSession req)throws GException {
		int online = (Integer) req.getTempData(PAR_ONLINE);
		if (online == Constants.STATUS_ONLINE) {
			doCheckSelf(req);
			return;
		}else {
			HashMap<String, PlayerVo> playerMap = PlayerService.doGetPlayerMap(req.getSid());
			if (playerMap == null) {
				req.setVO("regist", true);
			}else {
				List<PlayerVo> playerList = new ArrayList<PlayerVo>();
				for (Map.Entry<String, PlayerVo> entry : playerMap.entrySet()) {
					playerList.add(PlayerService.doTran2Vo(entry.getValue()));
				}
				req.setVO("player_list", playerList);
			}
			skipStatus(req, STATU_RETURN);
			return;
		}
	}

	@Override
	protected void doResponse(RequestSession req) throws GException {
		ObjMessage resp = req.getClientResponse();
		// 必须返回的全局变量
		resp.setVO(PAR_SID, req.getSid());
		resp.setCmd("p_S");
		response(req, resp);
	}


}
